import React, {useEffect} from 'react';
import {Button, DatePicker, Descriptions, message, Modal, notification, Select, TimePicker} from 'antd';
import axios from "axios";

const ReservationDialog = ({user, service, close}) => {
    const [api, contextHolder] = notification.useNotification();
    const [date, setDate] = React.useState(null);
    const [time, setTime] = React.useState(null);
    const [employee, setEmployee] = React.useState(null);
    const [employeeOptions, setEmployeeOptions] = React.useState([]);
    const userItem = [];
    const serviceItem = [];
    // 初始化钩子函数
    useEffect(() => {
        const getEmployeeOptions = async () => await axios
            .get('http://localhost:5532/serviceAndEmployee/getByService', {params: {serviceId: service.id}})
            .then(res => {
                return res.data.data.map(item => {
                    return {
                        value: item.employeeId,
                        label: item.employeeName,
                    }
                })
            });
        getEmployeeOptions().then(r => setEmployeeOptions(r));
    }, [])
    // 用户信息
    userItem.push(
        {
            key: 1,
            label: '用户名',
            children: user.name,
        },
        {
            key: 2,
            label: '手机号',
            children: user.phone,
        },
        {
            key: 3,
            label: '邮箱',
            children: user.email,
        },
    );
    // 服务信息
    serviceItem.push(
        {
            key: 1,
            label: '服务名称',
            children: service.name,
        },
        {
            key: 2,
            label: '服务价格',
            children: service.price,
        },
        {
            key: 3,
            label: '服务时间',
            children: service.duration,
        },
        {
            key: 4,
            label: '门店',
            children: '总店',
        },
    );


    const onDateChange = (date, dateString) => {
        console.log(dateString);
        setDate(dateString);
    };
    const onTimeChange = (time) => {
        if (time) {
            console.log(time.format('HH:mm:ss'));
            setTime(time.format('HH:mm:ss'));
        } else {
            setTime(null);
        }
    };
    const handleCancel = () => {
        close();
    }

    // 确认预约
    function handleOk() {
        // 支付定金 略 正规支付功能需要网站备案和个体工商户资质
        // 创建预约数据
        axios.post(
            'http://localhost:5532/appointment/userClient',
            {
                userId: user.id,
                serviceId: service.id,
                employeeId: employee,
                appointmentStatus: 'init',
                appointmentTime: date + 'T' + time,
                orderStatus: 'init',
                totalPrice: service.price,
            },
        ).then(res => {
            if (res.data.code === 1) {
                // 支付定金方法 略
                console.log('支付成功')
                axios({
                    method: 'post',
                    url: 'http://localhost:5532/payment',
                    data: {
                        orderId: res.data.data,
                        amount: service.price * 0.5,
                        paymentMethod: 'other',
                        transactionId: 'abcdefghijklmnopqrst',
                        status: 'success',
                    }
                }).then((res2) => {
                    if (res2.data.code === 1) {
                        message.success('预约成功，技师有时间冲突');
                        close();
                    }
                })
            } else {
                message.error('预约失败');
            }
        });
    }

    // 选择员工
    function handleSelectChange(value, option) {
        console.log(value, option)
        setEmployee(value);
    }
    const range = (start, end) => {
        const result = [];
        for (let i = start; i <= end; i++) {
            result.push(i);
        }
        return result;
    };
    return (
        <>
            <Modal
                closable={false}
                open={true}
                footer={(_) => (
                    <div style={{display: 'flex', width: '100%', justifyContent: 'space-between'}}>
                        <Button onClick={handleOk} type={'primary'}>确认预约</Button>
                        <Button onClick={handleCancel}>取消</Button>
                    </div>
                )}
            >
                <Descriptions title="用户信息" items={userItem}/>
                <br/>
                <Descriptions title="服务项目" items={serviceItem}/>
                <br/>
                <div style={{fontSize: '16px', fontWeight: 'bold', margin: '10px 0'}}>预约日期和时间</div>
                <DatePicker onChange={onDateChange}/>
                <br/>
                <TimePicker
                    onChange={onTimeChange}
                    showTime
                    disabledHours={() => range(0, 24).filter(h => h < 8 || h > 20)}
                />
                <br/>
                <div style={{fontSize: '16px', fontWeight: 'bold', margin: '10px 0'}}>心仪技师(没有可以不选)</div>
                <Select
                    defaultValue=''
                    style={{
                        width: 120,
                    }}
                    onChange={handleSelectChange}
                    options={employeeOptions}
                />
            </Modal>
        </>
    );
};
export default ReservationDialog;

